var express = require('express');
var router = express.Router();
var crypto = require('crypto');
var http = require('http');
var querystring = require('querystring');
var psmd5=require('blueimp-md5');
var query=require("../conn/conn");
const jwt=require('jsonwebtoken');
 
var md5 = crypto.createHash('md5')

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
router.get('/getsms', async (req, res, next)=>{
    // let resaaaa= await query("SELECT * FROM user")
    // res.send(resaaaa);
    let code=getCode();
    // fs.writeFile(path.join(__dirname, '..','public','temp',(req.query.phone)),code,'utf8',(err)=>{
    //     if(err){
    //         console.log(err);
    //     }else{
    //         send_sms('api.smsbao.com','809739979','daifancheng',`[千峰2107]您的验证码为：${code}`,req.query.phone)
            
    //         // res.send({msg:'发送成功',msgcode:0});
    //     }
        
    // })
    if(req.query.phone==''||req.query.phone=='undefined'||req.query.phone==undefined){
        return res.send({status:1,msg:'参数错误'});
    }else{
        send_sms('api.smsbao.com','809739979','daifancheng',`[千峰2107]您的验证码为：${code}`,req.query.phone)
        res.send({status:0,msg:"发送成功",code:code});
    }
    
    function send_sms(smsapi, user, password, content, phone) {
    var pass = md5.update(password).digest("hex");
    var data = {
      u: user,
      p: pass,
      m: phone,
      c: content,
    };
    var content = querystring.stringify(data);
    var sendmsg = "";
    var options = {
      hostname: smsapi,
      path: "/sms?" + content,
      method: "GET",
    };

    var req = http.request(options, function (res) {
      res.setEncoding("utf-8");
      res.on("data", function (result) {
        statusStr(result);
        // return(result)
      });
      res.on("end", function () {});
    });
    req.on("error", function (err) {
      console.error(err);
    });
    req.end();
  }

  function statusStr(result) {
    switch (result) {
      case "0":
        console.log("短信发送成功");
        res.send({ msg: "短信发送成功", code: "0" });
        break;
      case "-1":
        console.log("参数不全");
        res.send({ msg: "参数不全", code: "-1" });
        break;
      case "-2":
        console.log("");
        res.send({
          msg: "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
          code: "-2",
        });
        break;
      case "30":
        console.log("密码错误");
        res.send({ msg: "密码错误", code: "30" });
        break;
      case "40":
        console.log("账户不存在");
        res.send({ msg: "账户不存在", code: "40" });
        break;
      case "41":
        console.log("余额不足");
        res.send({ msg: "余额不足", code: "41" });
        break;
      case "42":
        console.log("账户已过期");
        res.send({ msg: "账户已过期", code: "42" });
        break;
      case "43":
        console.log("IP地址限制");
        res.send({ msg: "IP地址限制", code: "43" });
        break;
      case "50":
        console.log("内容含有敏感字");
        res.send({ msg: "内容含有敏感词", code: "50" });
        break;
    }
  }
  function random(min, max) {
    return Math.ceil(Math.random() * (max - min + 1) + min - 1);
  }
  function getCode() {
    var code = "";
    var type;
    for (var i = 0; i < 6; i++) {
      type = random(1, 3);
      switch (type) {
        case 1:
          code += String.fromCharCode(random(48, 57));
          break;
        case 2:
          code += String.fromCharCode(random(48, 57));
          break;
        case 3:
          code += String.fromCharCode(random(48, 57));
          break;
      }
    }
    return code;
  }
});

router.post('/register',async(req,res,next)=>{
    if(req.body.phone==""||req.body.phone==undefined||req.body.phone=="undefined"||req.body.username==""||req.body.username==undefined||req.body.username=="undefined"||req.body.password==""||req.body.password==undefined||req.body.password=="undefined"||req.body.zfmm==""||req.body.zfmm==undefined||req.body.zfmm=="undefined"){
        res.send({status:1,msg:"参数错误"});
    };
    console.log(req.body)
//   let ress=await query(`INSERT INTO user( phone, user, password, token ) VALUES ('${req.body.phone}','${req.body.username}','${psmd5(req.body.password+'gege332')}','123')`)
//   let resss=await query(`SELECT * FROM user WHERE phone='${req.body.phone}'`);
//   if(resss.length>0){
//       res.send({status:1,msg:"手机号已存在",resss});
//   }else{
//     res.send({status:0,msg:'注册成功',resss});
//   }
    new Promise(async function (resolve, reject) {
        let resss = await query(
          `SELECT * FROM user WHERE phone='${req.body.phone}'`
        );
        console.log(resss)
        if (resss.length > 0) {
          res.send({ status: 1, msg: "手机号已存在" });
        } else {
            let phone=req.body.phone;
            let key="gege332";
            let token=jwt.sign(phone,key);
            // new Promise( async (resolve,reject)=>{
            let ress = await query(`INSERT INTO user( phone, user, password, token, zfmm) VALUES ('${req.body.phone}','${req.body.username}','${psmd5(req.body.password + "gege332")}','${token}','${req.body.zfmm}')`);
            res.send({ status: 0, msg: "注册成功" });
            // });
        }
    })
});

router.post('/login',async(req,res,next)=>{
    if(req.body.phone==""||req.body.phone==undefined||req.body.phone=="undefined"||req.body.password==""||req.body.password==undefined||req.body.password=="undefined"){
        res.send({status:1,msg:"参数错误"});
    };
    let ress=await query(`SELECT * FROM user WHERE phone='${req.body.phone}' and password='${psmd5(req.body.password+'gege332')}'`);
    if(ress.length>0){
        let phone=req.body.phone;
        let key="gege332";
        let token=jwt.sign(phone,key);
        res.send({status:0,msg:"登陆成功",token})
    }else{
        res.send({status:1,msg:"账号或密码错误"})
    }
});
router.post('/token',async (req,res,next)=>{
    let token=req.body?.token;
    let zfmm=req.body?.zfmm;
    if(zfmm==undefined||zfmm=="undefined"){
        let ress=await query(`SELECT * FROM user WHERE token='${token}'`);
        if(ress.length==1){
            res.send({status:0,msg:"查询成功,当前token存在"})
        }else{
            res.send({status:101,msg:"查询失败,当前token不存在"})
        }
    }else{
        let resss=await query(`SELECT * FROM user WHERE token='${token}' and zfmm='${zfmm}'`);
        if(resss.length>0){
            res.send({status:0,msg:"查询成功,token和zfmm匹配"});
        }else{
            res.send({status:102,msg:"查询失败,token和zfmm不匹配"})
        }
    }
})

router.post('/getshop',async(req,res,next)=>{
    let ress=await query(`INSERT INTO shop (username, shop) VALUES ('${req.body.username}', '${req.body.shop}')`);
    res.send({status:0,msg:"数据加入成功"});
});

router.get('/getshopdata',async(req,res,next)=>{
    let ress=await query(`SELECT * FROM shop WHERE username='${req.query.username}'`);
    if(ress.length>0){
        res.send({status:0,msg:"请求成功",result:ress});
    }else{
        res.send({status:1,msg:"参数错误"})
    }
    
})

module.exports = router;
